package chat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws InterruptedException, IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9960);
        System.out.println("启动新的客户端。");

        Receive receive = new Receive(socket);
        receive.start();

        Send send = new Send(socket);
        send.start();

        send.join(); // 阻塞主线程  等发送线程结束，才结束整个程序
        socket.close();
    }
}

class Receive extends Thread {
    Socket socket;

    @Override
    public void run() {
        try (InputStream inputStream = socket.getInputStream();
             Scanner scanner = new Scanner(inputStream)) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public Receive(Socket socket) {
        this.socket = socket;
    }
}

class Send extends Thread {
    Socket socket;

    @Override
    public void run() {

        try (Scanner scan = new Scanner(System.in)) {
            OutputStream outputStream = socket.getOutputStream();
            PrintStream printStream = new PrintStream(outputStream);
            while (true) {
                System.out.print("我：");
                String next = scan.nextLine();
                if (next.equals("exit")) {
                    break;
                }
                printStream.println(next);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public Send(Socket socket) {
        this.socket = socket;
    }

}


